package pers.leeyns.cms.baidu;

import java.io.IOException;
import java.io.StringReader;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Security;
import java.security.interfaces.RSAPublicKey;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMReader;

import sun.misc.BASE64Encoder;

public class RSAUtils {
	private static Cipher cipher;  
    
    static{  
        try {  
            cipher = Cipher.getInstance("RSA");  
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
        } catch (NoSuchPaddingException e) {  
            e.printStackTrace();  
        }  
    }  
/*
 public key PEM格式
 
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCa8GvvbkLe8WULC8LH2GPXR9Om
g+bIucircYsmbEu8hmZK/5Jg5F/buasF+p1k8tDBpwAxpaDVEZ007exEi4qulWnW
8YJySiXlH0FuQGA/zrn2X16MR7VxLqGrBMw/EOUIGZqnMORqUytA4pIy1mf/ZXbF
6Zml/+vCAn4W8rAiWQIDAQAB
-----END PUBLIC KEY-----

*/
	/**
	 * 获取public key
	 * @param publicKey
	 * @return
	 * @throws IOException
	 */
	public static RSAPublicKey getPublicKey(String publicKey) throws IOException {
		Security.addProvider(new BouncyCastleProvider());
		@SuppressWarnings("resource")
		PEMReader pemReader = new PEMReader(new StringReader(publicKey));
		RSAPublicKey rsaPubKey = (RSAPublicKey) pemReader.readObject();
		System.out.println("Public key: " + rsaPubKey);
		return rsaPubKey;
	}
	
    /** 
     * 使用公钥对明文进行加密，返回BASE64编码的字符串 
     * @param publicKey 
     * @param plainText 
     * @return 
     */  
    public static String encrypt(PublicKey publicKey,String plainText){  
        try {             
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
            byte[] enBytes = cipher.doFinal(plainText.getBytes());            
            return (new BASE64Encoder()).encode(enBytes);  
        } catch (InvalidKeyException e) {  
            e.printStackTrace();  
        } catch (IllegalBlockSizeException e) {  
            e.printStackTrace();  
        } catch (BadPaddingException e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  
    
    /**
     * RSA 公钥加密
     * @param pubKey 公钥
     * @param signText 需要加密的字符串
     * @return
     */
    public static String encrypt(String pubKey,String signText){
    	PublicKey publicKey;
		try {
			publicKey = getPublicKey(pubKey);
			return encrypt(publicKey, signText);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
    }
}
